<?php

namespace app\api\controller;

use app\common\controller\Alisms;
use app\common\model\Banner;
use app\common\model\FileLog;
use think\Db;
use think\facade\Config;
use app\common\model\User;
use app\common\controller\Handle;
use app\common\model\LoginLog;
//首页控制器
class ApiLogin extends ApiTop
{
    //登录
    public function login()
    {
        
        $post = request()->post();
        $wx_config = Config::get('sysconfig');
        $appid = $wx_config['wx_appid'];
        $appsecret = $wx_config['wx_appsecret'];
        if (!isset($post['code'])) {
            return json(['status' => 0, 'msg' => '缺少code参数']);
        }

        $code = $post['code'];
        $hand = new Handle();
        $sesskeyarr = $hand->sendCode($appid, $appsecret, $code);

        if(empty($sesskeyarr['openid'])){
            return json(['status' => 0, 'msg' => '获取openid失败']);
        }

        $userModel = new User();
        $user = $userModel->getOne(['openid'=> $sesskeyarr['openid']]);
        if($user){
            $token = md5($user['id'] . time() . $user['add_time']);
            $userModel->update(['id'=>$user['id'],'token'=>$token]);
            cache($token, $user['id'],86400);
            
        }else{
            $add = [];
            $add['openid'] = $sesskeyarr['openid'];
            $add['add_time'] = time();
            $user = $userModel->create($add);
            $number = 100000000 + $user->id;
            $token = md5($user->id . time() . $add['add_time']);
            $userModel->update(['id'=>$user->id,'token'=>$token,'number'=>$number,'nickname'=>'微信用户_'.substr($add['add_time'], -4).$user->id]);
            cache($token, $user->id,86400);
        }
        $year = date("Y");
        $month = date("m");
        $ri = date("d");

        
        $loginLogModel = new LoginLog();

        $where['YYY'] =  $year;
        $where['MMM'] =  $month;
        $where['DDD'] =  $ri;
        $where['user_id'] =  $user->id;

        $find = $loginLogModel->where($where)->find();

        if(empty($find)){
            $add['YYY'] = $year;
            $add['MMM'] = $month;
            $add['DDD'] = $ri;
            $add['user_id'] = $user->id;
            $add['created_at'] = date("Y-m-d H:i:s");
            $add['update_at'] = date("Y-m-d H:i:s");
            $res =  $loginLogModel->insert($add);
        }
        
        return json(['status'=> 1,'msg'=> '成功','token'=>$token]);
        
        // if ($res) {
        //     $res['cover_img'] = 'https://' . config('uwind.domain.url') . $res['cover_img'];
        //     return json(['status' => 1, 'data' => $res]);
        // } else {
        //     return json(['status' => 0]);
        // }
    }
}
